package com.sixmac.controller;

import com.sixmac.annotation.AuthUser;
import com.sixmac.common.model.system.Attach;
import com.sixmac.common.vo.ShiroUser;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.constant.ConstConfig;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.Func;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.cache.CacheKit;
import com.sixmac.core.toolbox.file.BladeFileKit;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.model.User;
import com.sixmac.service.UserService;
import com.sixmac.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * UserController
 * 2018-06-09 09:57:44
 *
 * @author Blade
 */
@Controller
@ResponseBody
public class UserController extends ApiController {
    @Autowired
    UserService userService;

    /**
     * @api {post} /api/myThumbs  我点赞列表
     * @apiName my.myThumbs
     * @apiGroup my
     * @apiParam {String}  token  token
     * @apiParam {String}  page  当前页 默认 1
     * @apiParam {String}  size  每页大小 默认 2
     * @apiSuccess {String} data.rows.id 文章id
     * @apiSuccess {String} data.rows.img 封面图片
     * @apiSuccess {String} data.rows.title 标题
     * @apiSuccess {String} data.rows.length 视频播放时间
     * @apiSuccess {String} data.rows.url 地址
     * @apiSuccess {String} data.rows.content 内容
     * @apiSuccess {String} data.rows.palynum 播放量
     * @apiSuccess {String} data.rows.thumbsnum 点赞量
     * @apiError {Integer} 1
     */
    @RequestMapping("/myThumbs")
    @AuthUser
    public AjaxResult myThumbs(User user, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "3") Integer size) {
        BladePage<Map> maps = Db.paginate("select c.* from t_content c inner join t_thumbs t on t.articleId = c.id where t.userId =" + user.getId() + " order by c.createDate desc", null, page, size);
        return new AjaxResult().setData(maps);
    }

    /**
     * @api {post} /api/myCollections  我收藏列表
     * @apiName my.myCollections
     * @apiGroup my
     * @apiParam {String}  token  token
     * @apiParam {String}  page  当前页 默认 1
     * @apiParam {String}  size  每页大小 默认 2
     * @apiSuccess {String} data.rows.id 文章id
     * @apiSuccess {String} data.rows.img 封面图片
     * @apiSuccess {String} data.rows.title 标题
     * @apiSuccess {String} data.rows.length 视频播放时间
     * @apiSuccess {String} data.rows.url 地址
     * @apiSuccess {String} data.rows.content 内容
     * @apiSuccess {String} data.rows.palynum 播放量
     * @apiSuccess {String} data.rows.thumbsnum 点赞量
     * @apiError {Integer} 1
     */
    @AuthUser
    @RequestMapping("/myCollections")
    public AjaxResult myCollections(User user, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "3") Integer size) {
        BladePage<Map> maps = Db.paginate("select c.* from t_content c inner join t_collections t on t.articleId = c.id where t.userId =" + user.getId() + " order by c.createDate desc", null, page, size);
        return new AjaxResult().setData(maps);
    }

    /**
     * @api {post} /api/updateUser  修改用户信息
     * @apiName my.updateUser
     * @apiGroup my
     * @apiParam {String}  token  token
     * @apiParam {String}  nickname  用户昵称
     * @apiParam {String}  sign  签名
     * @apiParam {String}  headimg  头像
     * @apiError {Integer} 1
     */
    @AuthUser
    @RequestMapping("/updateUser")
    public AjaxResult updateUser(User u, String nickname, String sign, String headimg) {
        AjaxResult res = new AjaxResult();
        User user = new User();
        user.setId(u.getId());
        user.setNickname(nickname);
        user.setSign(sign);
        user.setHeadimg(headimg);
        Boolean b = Blade.create(User.class).update(user);
        if (b) {
            res.addSuccess("修改成功");
        } else {
            res.addError("修改失败");
        }
        return res;
    }

    /**
     * @api {post} /api/editMobile  修改手机号码
     * @apiName my.editMobile
     * @apiGroup my
     * @apiParam {String}  token  token
     * @apiParam {String}  newMobile  新手机号码
     * @apiParam {String}  captcha  验证码
     * @apiError {Integer} 1
     */
    @AuthUser
    @RequestMapping("/editMobile")
    @Validator(name = {"newMobile", "captcha"}, format = {Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult editMobile(User u, String newMobile, String captcha) {
        AjaxResult res = new AjaxResult();
        User user = new User();
        user.setId(u.getId());
        if (userService.verifyCaptcha(newMobile, captcha)) {
            if (!userService.verifyMobile(newMobile)) {
                return res.addError("手机号码已存在");
            }
            user.setMobile(newMobile);
            Blade.create(User.class).update(user);
            return res.addSuccess("修改成功");
        }
        return res.addError("修改失败");
    }

    /**
     * @api {post} /api/logout  退出
     * @apiName my.logout
     * @apiGroup my
     * @apiParam {String}  token  token
     * @apiError {Integer} 1
     */
    @RequestMapping("/logout")
    @ResponseBody
    @AuthUser
    public AjaxResult logout(User user) {
        CacheKit.remove(ConstCache.SYS_USER + ConstCacheKey.USER_AUTH_TOKEN, user.getToken());
        return success("退出成功");
    }


    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    /**
     * @api {post} /api/upload_json  上传图片1
     * @apiName my.upload_json
     * @apiGroup my
     * @apiParam {File}  imgFile   图片
     * @apiSuccess {String} url 图片地址
     * @apiError {Integer} 1
     */
    @RequestMapping("/upload_json")
    public CMap upload_json(@RequestParam("imgFile") MultipartFile file, HttpServletRequest request) {
        CMap cmap = CMap.init();
        if (null == file) {
            cmap.set("error", 1);
            cmap.set("message", "请选择要上传的文件");
            return cmap;
        }
        String originalFileName = file.getOriginalFilename();
        String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
        String dir = getParameter("dir", "image");
        // 测试后缀
        boolean ok = BladeFileKit.testExt(dir, originalFileName);

        if (!ok) {
            cmap.set("error", 1);
            cmap.set("message", "上传文件的类型不允许");
            return cmap;
        }

        String path = FileUploadUtil.uploadFile(file);
        System.out.println("******" + path);

        if (StringUtils.isEmpty(path)) {
            cmap.set("error", 1);
            cmap.set("message", "上传失败");
            return cmap;
        }

        Attach attach = new Attach();
        ShiroUser user = ShiroKit.getUser();
        Object creater = (null == user) ? 0 : user.getId();
        attach.setCreater(Func.toInt(creater));
        attach.setCreatetime(new Date());
        attach.setName(originalFileName);
        attach.setStatus(1);
        attach.setUrl(path);
        Blade.create(Attach.class).saveRtStrId(attach);

        cmap.set("error", 0);
        cmap.set("title", "");
        cmap.set("url", ConstConfig.UPLOAD_PATH + path);
        cmap.set("name", originalFileName);
        System.out.println(cmap);
        return cmap;

    }







}
